package com.wk.security_practice.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.wk.security_practice.entity.User;
import com.wk.security_practice.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
@CrossOrigin
public class TestController {
    @Autowired
    private LoginService loginService;

    @RequestMapping("/test")
    public Object test (@RequestParam Map<String, Object> params) {
        System.out.println(params.get("username"));
        List<User> userList = loginService.getUserByUsername("admin");
        ObjectMapper mapper = new ObjectMapper();
        String jsonlist = null;
        try {
            jsonlist = mapper.writeValueAsString(userList);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return jsonlist;
    }

    @RequestMapping("/test3")
    public Object test3(@RequestParam Map<String, String> map) throws JsonProcessingException {
        System.out.println(map.get("username"));
        User user = new User();
        user.setUsername("小民");
        user.setPassword("123");

        User user2 = new User();
        user2.setUsername("小李");
        user2.setPassword("456");


        ObjectMapper mapper = new ObjectMapper();

        //User类转JSON
        //输出结果：{"name":"小民","age":20,"birthday":844099200000,"email":"xiaomin@sina.com"}
        String json = mapper.writeValueAsString(user);
        System.out.println(json);

        //Java集合转JSON
        //输出结果：[{"name":"小民","age":20,"birthday":844099200000,"email":"xiaomin@sina.com"}]
        List<User> users = new ArrayList<User>();
        users.add(user);
        users.add(user2);
        String jsonlist = mapper.writeValueAsString(users);
        return jsonlist;
    }
}

